//
//  YPDownloadManager.m
//  KingSelected
//
//  Created by 杨鹏 on 2023/11/1.
//

#import "YPDownloadManager.h"
#import <FGGDownloader/FGGDownloader.h>

static YPDownloadManager *_instance = nil;
static dispatch_once_t onceToken;

@implementation YPDownloadManager

+ (YPDownloadManager *)sharedDownloadManager {
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

- (instancetype)init {
    if (self = [super init]) {
        
    }
    return self;
}

- (void)downloadImageWithUrl:(NSString *)url {
    if (url.length <= 0) {
        return;
    }
    NSString *document = [self getPathWithName:@"image"];
    NSString *topath = [document stringByAppendingPathComponent:[url lastPathComponent]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:topath]) {
        return;
    }
    [[FGGDownloader downloader] downloadWithUrlString:url toPath:topath process:^(float progress, NSString *sizeString, NSString *speedString) {
//        NSLog(@"progress== %f",progress);
    } completion:^{
        NSLog(@"下载完成");
    } failure:^(NSError *error) {
        NSLog(@"下载失败");
    }];
}

- (NSString *)getImagePathWithUrl:(NSString *)url {
    NSString *document = [self getPathWithName:@"image"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:document]) {
        NSArray *fileArr = [self getFileListWithPath:document deep:NO];
        if (fileArr.count <= 0) {
            return nil;
        }
        if ([fileArr containsObject:url.lastPathComponent]) {
            return [document stringByAppendingString:url.lastPathComponent];
        }
    }
    return nil;
}

- (NSString *)getPathWithName:(NSString *)name {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *document = paths.firstObject;
    document = [document stringByAppendingFormat:@"/%@/",name];
    if (![[NSFileManager defaultManager] fileExistsAtPath:document]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:document withIntermediateDirectories:NO attributes:nil error:nil];
    }
    return document;
}

- (NSArray *)getFileListWithPath:(NSString *)path deep:(BOOL)deep {
    NSArray *fileList;
    NSError *err;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (deep) {
        NSArray *deepArr = [fileManager subpathsOfDirectoryAtPath:path error:&err];
        if (!err) {
            fileList = deepArr;
        }else {
            fileList = nil;
        }
    }else {
        NSArray *qianArr = [fileManager contentsOfDirectoryAtPath:path error:&err];
        if (!err) {
            fileList = qianArr;
        }else {
            fileList = nil;
        }
    }
    return fileList;
}
@end
